const SpiderBaseClass = require('./SpiderBaseClass');

const listSize = 120;//列表页面有多少个主播信息
class SpiderHuYa extends SpiderBaseClass {

  static firstListPage() {
    return 1;
  }

  /**
   * 获取其它页码的列表页面
   * @param page
   */
  static async getListPage(page) {

    const res = await SpiderHuYa.get(SpiderHuYa.listPageUrl(page),
      {dataType: 'json'});

    const list = res.data.data.datas.map(
      room => {
        return {
          anchor: {
            room: room.profileRoom,
            name: room.nick,
            avatar: room.avatar180,
            gender: 0,
          },
          type: room.gameFullName,
          data: {
            num_watch: SpiderHuYa.toNumber(room.totalCount),
            num_live: 0,
            num_follower: 0,
            num_gift: 0,
          },
        };
      });
    return {
      list,
      page,
      getMoreInfo: true,
      nextPage: page + 1,
      hasNextPage: list.length >= listSize,
    };
  }

  /**
   * 获取直播间信息
   * @param room
   */
  static async getRoom(room) {
    const res = await SpiderHuYa.get(SpiderHuYa.roomUrl(room.anchor.room),
      {dataType: 'text'});

    //性别,1男，2女
    {
      const match = res.data.match(/sex":"(\d)/);
      if (match && match[1] && ['1', '2'].indexOf(match[1]) !== -1)
        room.anchor.gender = match[1];
    }

    //粉丝
    {
      const match = res.data.match(/fans":(\d+)/);
      if (match && match[1])
        room.data.num_follower = SpiderHuYa.toNumber(match[1]);
    }

  }

  /**
   * 生成列表页面的网址
   * @param page
   * @return string
   */
  static listPageUrl(page) {
    return 'https://www.huya.com/cache.php?m=LiveList&do=getLiveListByPage&tagAll=0&page=' +
      page;
  }

  /**
   * 生成直播间信息的网址
   * @param id
   * @return string
   */
  static roomUrl(id) {
    return 'https://www.huya.com/' + id;
  }

}

module.exports = SpiderHuYa;